package com.site.controller.manage;

import com.common.encryt.MD5;
import com.common.exception.BusinessException;
import com.common.util.SecreUtil;
import com.site.model.User;
import com.site.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by robin on 2016/12/22.
 * 登录controller
 */
@Controller
public class UserController {
    @Autowired
    private UserService service;

    @RequestMapping("m/login")
    @ResponseBody
    public int login(String name,String pwd,String code){
        if(StringUtils.isBlank(name) || StringUtils.isBlank(pwd) || StringUtils.isBlank(code))return 0;
        String sessionCode = SecreUtil.getSessionValue("vailCode")+"";
        if(!sessionCode.toLowerCase().equals(code.toLowerCase())){
           return 1;
        }else{
            UsernamePasswordToken token = new UsernamePasswordToken(name, MD5.MD5Encode(pwd));
            Subject subject= SecurityUtils.getSubject();
            subject.login(token);
        }
        return 2;
    }

    @RequestMapping("user/save")
    @ResponseBody
    public int save(String name,String pwd,String nickname){
        User user = new User();
        user.setUserName(name);
        user.setUserPassword(MD5.MD5Encode(pwd));
        user.setUserNickname(nickname);
        return service.save(user);
    }

    @RequestMapping("user/updatePwd")
    @ResponseBody
    public int updatePwd(String oldPwd,String newPwd){
        String sessionPwd = ((Map)SecreUtil.getSessionValue(SecreUtil.SessionAtrr.USERMAP)).get("password")+"";
        if(!sessionPwd.equals(MD5.MD5Encode(oldPwd))) throw new BusinessException("原密码错误");
        service.updatePwd(SecreUtil.getUserId(),MD5.MD5Encode(newPwd));
        SecurityUtils.getSubject().logout();
        return 1;
    }

    @RequestMapping("logout")
    @ResponseBody
    public int logout(){
        SecurityUtils.getSubject().logout();
        return 1;
    }

    @RequestMapping("user/savePage")
    public String savePage(){
        return "manage/user/saveUser";
    }

    @RequestMapping("user/updatePwdPage")
    public String updatePwdPage(){
        return "manage/user/updatePwd";
    }
}
